﻿using AutoMapper;
using IMES.Common.Domain.DariusModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using NPOI.SS.Formula.Functions;

namespace Darius.API.Application.Commands
{
    public class RolePermissionCreateHandler : IRequestHandler<RolePermissionCreateCommand, ResultT<RoleCreateDto>>
    {
        private readonly IBaseRepositorys<RolesPermission> rolePermissionRepository;
        private readonly IMapper mapper;
        private readonly IBaseRepositorys<Roles> roleRepository;
        private readonly ILogger<RolePermissionCreateHandler> logger;

        public RolePermissionCreateHandler(IBaseRepositorys<RolesPermission> rolePermissionRepository, IBaseRepositorys<Roles> roleRepository, IMapper mapper, ILogger<RolePermissionCreateHandler> logger)
        {
            this.rolePermissionRepository = rolePermissionRepository;
            this.mapper = mapper;
            this.logger = logger;
            this.roleRepository = roleRepository;
        }
        /// <summary>
        /// 角色权限添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultT<RoleCreateDto>> Handle(RolePermissionCreateCommand request, CancellationToken cancellationToken)
        {
            var res = 0;
           try
            {
                var result = new ResultT<RoleCreateDto>() { Code=(int)CodeEnum.add};

                Roles roles = new Roles()
                {
                    
                    RoleName = request.RoleName,
                    DepartmentName = request.DepartmentName,
                    Pid = request.Pid,

                };
                res+=roleRepository.Add(roles);
                foreach (var item in request.Ids)
                {
                    var list = roleRepository.GetAll().Select(x=>x.RoleId).ToList();
                    int a = list.Max();
                    var rolePermission = new RolesPermission()
                    {
                       
                        RoleId=a,
                        PermissionId = item,
                    };
                    res+=rolePermissionRepository.Add(rolePermission);                 
                }
                result.Messege = "添加角色权限成功";
                result.Code = res;
                logger.LogInformation(result.Messege);
                return result;
                
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "添加角色权限失败");
                return new ResultT<RoleCreateDto>() { Code = (int)CodeEnum.error, Messege = "添加角色权限失败" };
            }
        }
    }
}
